package com.douwong.student.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;



import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.xutils.common.Callback;
import org.xutils.x;
import org.xutils.http.RequestParams;

import java.util.List;
import java.util.Map;

/**
 * @autor yichao
 * @time 2017/3/2313:41
 * @des 网络工具类
 */
public class NetUtils {
    private static final String TAG = "NetUtils";
    private final static int TIMEOUT_CONNECTION = 8000;
    private final static int TIMEOUT_SOCKET = 15000;
    public static final String UTF_8 = "UTF-8";
    private final static int RETRY_TIME = 0; // 不重新连接

    /**
     * 网络是否可用
     * @param context
     * @return
     */
    public static boolean NetwrokIsUseful(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {

            Log.v("error", e.toString());
        }
        return false;
    }

    /**
     * 是否使用wifi连接
     * @param context
     * @return
     */
    public static boolean isWIFINetWork(Context context) {
        try {

            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            if (connectivity != null) {
                NetworkInfo wifi = connectivity
                        .getNetworkInfo(ConnectivityManager.TYPE_WIFI); // wifi
                // NetworkInfo gprs =
                // connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                // // gprs
                if (wifi != null && wifi.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        } catch (Exception e) {
            Log.v("error", e.toString());
        }
        return false;
    }
    /**
     * 本地ip
     * @return
     */
    public static String getlocalip(Context context){
        WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        Log.i(TAG, "int ip "+ipAddress);
        if(ipAddress==0)return "";
        return ((ipAddress & 0xff)+"."+(ipAddress>>8 & 0xff)+"."
                +(ipAddress>>16 & 0xff)+"."+(ipAddress>>24 & 0xff));
    }

    /**
     * 获取mac
     * @param context
     * @return
     */
    public static String getMac(Context context) {

        WifiManager wifi = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);

        WifiInfo info = wifi.getConnectionInfo();

        return info.getMacAddress();

    }
    // get方法
    public static String httpGet(String url, List<BasicNameValuePair> params) {
        String response = null;
        int time = 0;
        do {
            String param = URLEncodedUtils.format(params, UTF_8);
            HttpGet httpGet = new HttpGet(url + "?" + param);

            HttpClient httpClient = getHttpClient();
            try {
                HttpResponse httpResponse = httpClient.execute(httpGet);
                int stautsCode = httpResponse.getStatusLine().getStatusCode();

                if (stautsCode == HttpStatus.SC_OK) {
                    response = EntityUtils.toString(httpResponse.getEntity(), UTF_8);

                    break;
                } else {
                    // stauts con fail
                }
            } catch (Exception e) {
                time++;
                if (time < RETRY_TIME) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                    }
                    continue;
                }
                e.printStackTrace();
                // tell client error
            }

        } while (time < RETRY_TIME);

        return response;
    }
    // post方法
    public static String httpPost(String url, List<BasicNameValuePair> params) throws Exception {
        String response = null;
        int time = 0;

        do {
            HttpEntity entity = new UrlEncodedFormEntity(params, UTF_8);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(entity);
            // String param=URLEncodedUtils.format(params, UTF_8);
            // HttpPost httpPost=new HttpPost(url+"?"+param);
            // Log.d("asd", httpPost.getURI().toString());
            HttpClient httpClient = getHttpClient();

            try {
                HttpResponse httpResponse = httpClient.execute(httpPost);
                int stautsCode = httpResponse.getStatusLine().getStatusCode();

                if (stautsCode == HttpStatus.SC_OK) {
                    response = EntityUtils.toString(httpResponse.getEntity(), UTF_8);
                    break;
                } else {
                    // stauts con fail
                }

            } catch (Exception e) {
                time++;
                if (time < RETRY_TIME) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    continue;
                }
                e.printStackTrace();
                throw new Exception(e);
                // tell client erro
            }

        } while (time < RETRY_TIME);

        return response;
    }

    private static HttpClient getHttpClient() {

        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_CONNECTION);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SOCKET);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        return httpClient;
    }

    /**
     * 发送get请求
     * @param <T>
     */
    public static <T> Callback.Cancelable Get(String url, Map<String,String> map, Callback.CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        if(null!=map){
            for(Map.Entry<String, String> entry : map.entrySet()){
                params.addQueryStringParameter(entry.getKey(), entry.getValue());
            }
        }
        Callback.Cancelable cancelable = x.http().get(params, callback);


        return cancelable;
    }
    /**
     * 发送post请求
     * @param <T>
     */
    public static <T> Callback.Cancelable Post(String url, Map<String,Object> map, Callback.CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        if(null!=map){
            for(Map.Entry<String, Object> entry : map.entrySet()){
                params.addParameter(entry.getKey(), entry.getValue());
            }
        }
        Callback.Cancelable cancelable = x.http().post(params, callback);
        return cancelable;
    }
}
